package com.laomuji.android.mvvm.utils

import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.provider.Settings
import androidx.core.net.toUri
import com.laomuji.android.mvvm.base.BaseActivity
import com.laomuji.android.mvvm.base.BaseApplication

/**
 * 一些App间的操作
 * @author laomuji666
 * @since 2024/2/21
 */
class AppUtil {
    /**
     * 跳转网页
     */
    fun jumpUrl(url: String) {
        val topActivity: BaseActivity<*, *> = PackageUtil.getTopActivity()
        val it = Intent()
        it.setAction("android.intent.action.VIEW")
        val uri = url.toUri()
        it.setData(uri)
        topActivity.startActivity(it)
    }

    /**
     * 跳转谷歌商店
     */
    @SuppressLint("QueryPermissionsNeeded")
    fun jumpGooglePlay(packageName: String) {
        val context: Context = BaseApplication.instance!!.getTopActivity()
        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setData("market://details?id=$packageName".toUri())
            intent.setPackage("com.android.vending")
            if (intent.resolveActivity(context.packageManager) != null) {
                context.startActivity(intent)
            } else {
                jumpUrl("https://play.google.com/store/apps/details?id=$packageName")
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 是否安装了某个app
     * 部分手机需要在Manifest文件标签下填写对应的包名
     * <queries>
     * <package android:name="对应的应用的包名"></package>
    </queries> *
     * @param packageName APP的包名
     * @return 是否安装
     */
    fun isInstallApp(packageName: String?): Boolean {
        if (packageName == null) {
            return false
        }
        try {
            BaseApplication.instance!!.getTopActivity().packageManager
                .getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            return false
        } catch (e: Exception) {
            return true
        }
        return true
    }

    /**
     * 获取安卓ID作为唯一标识,不需要权限
     * 可能有部分手机返回null或者""
     * @return AndroidId
     */
    fun getAndroidID(contentResolver: ContentResolver?): String? {
        return if (contentResolver == null) {
            null
        } else try {
            @SuppressLint("HardwareIds") val id =
                Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
            if ("9774d56d682e549c" == id) null else id
        } catch (e: Exception) {
            null
        }
    }
}

